package cn.hty.mymsg.api.service;

import cn.hty.mymsg.common.constant.AustinConstant;
import cn.hty.mymsg.common.domain.SimpleAnchorInfo;
import cn.hty.mymsg.common.enums.RespStatusEnum;
import cn.hty.mymsg.service.domain.TraceResponse;
import cn.hty.mymsg.service.service.TraceService;
import cn.hty.mymsg.utils.RedisUtils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class TraceServiceImpl implements TraceService {

    @Autowired
    private RedisUtils redisUtils;
    /**
     * 通过messageId获取链路信息
     */
    @Override
    public TraceResponse traceByMessageId(String messageId) {
        if (CharSequenceUtil.isBlank(messageId)){
            return new TraceResponse(RespStatusEnum.CLIENT_BAD_PARAMETERS.getCode(), RespStatusEnum.CLIENT_BAD_PARAMETERS.getMsg(), null);
        }
        String redisKey = CharSequenceUtil.join(StrUtil.COLON, AustinConstant.CACHE_KEY_PREFIX, AustinConstant.MESSAGE_ID, messageId);
        List<String> messageList = redisUtils.lRange(redisKey, 0, -1);
        if (CollUtil.isEmpty(messageList)){
            return new TraceResponse(RespStatusEnum.FAIL.getCode(), RespStatusEnum.FAIL.getMsg(), null);
        }
        List<SimpleAnchorInfo> sortAnchorList  = messageList.stream()
                .map(s -> JSON.parseObject(s, SimpleAnchorInfo.class))
                .sorted((o1, o2) -> Math.toIntExact(o1.getTimestamp() - o2.getTimestamp())).collect(Collectors.toList());
        return new TraceResponse(RespStatusEnum.SUCCESS.getCode(), RespStatusEnum.SUCCESS.getMsg(), sortAnchorList);
    }
}
